const moment=require('moment');
const get=(uri,cb)=>{
    setTimeout(()=>{
        cb(uri);
    },2000/*Math.random()*3000|0*/);
};


let list=[1,2,3,4,5];

const mapLimit=(list=[],limit=2,each,cb)=>{
    if(!Array.isArray(list))return cb('List is must b an array');
    let ret=[],cnt=0,ing=0;
    (function iife(i){
        for(;i<list.length;i++){
            if(ing>=limit)break;

            each(list[i],(idx=>(err,res)=>{
                if(err)return cb(err,ret);

                ret[idx]=res;
                cnt++;

                if(cnt==list.length)return cb(null,ret);

                if(0==cnt%limit){
                    ing=0;
                    iife(i);
                }
            })(i));
            ing++;
        }
    })(0);
};

mapLimit(list,2,(item,cb)=>{
    console.log('each item:',item,moment().format('HH:mm:ss.SSS'));
    get('http://'+item+'.com',ret=>{
        cb(null,ret);
    });
},(err,ret)=>{
    console.log('ret:',err,ret);
});
